<?php

namespace MicroCyan\MQTT\Kernel;

class App
{
    public function connect($options=[]): \PhpMqtt\Client\MqttClient
    {
        $mqttConfig = config('mc.mqtt');
        $config = [ 'host'=>'', 'port'=>1883, 'username'=>'', 'password'=>'' ];
        foreach ($config as $k => $v){
            if (!empty($options[$k])){
                $config[$k] = $options[$k];
                continue;
            }else if (!empty($mqttConfig[$k])){
                $config[$k] = $mqttConfig[$k];
                continue;
            }
        }
        $clientId = $options['clientId']??'';
        if (empty($clientId)){
            $clientId = mt_rand(0,9999).'_'.mt_rand(0,999).'_'.microtime(true);
            $clientId = md5($clientId);
            $clientId = 'mc_'.$clientId;
            $clientId = substr($clientId,0,20);
        }
        $mqtt = new \PhpMqtt\Client\MqttClient($config['host'], $config['port'], $clientId);
        $connectionSettings = (new \PhpMqtt\Client\ConnectionSettings())
            ->setUsername(empty($config['username'])?null:$config['username'])
            ->setPassword(empty($config['password'])?null:$config['password']);
        $mqtt->connect($connectionSettings);
        return $mqtt;
    }

}